#pragma once

#include <linux/container_of.h>
#include <linux/rbtree_types.h>

#define rb_parent(r) ((struct rb_node *)((r)->__rb_parent_color & ~3))

#define rb_entry(ptr, type, member) container_of(ptr, type, member)

#define RB_EMPTY_ROOT(root)  (READ_ONCE((root)->rb_node) == NULL)

/* Same as rb_first(), but O(1) */
#define rb_first_cached(root) ((root)->rb_leftmost)

/* 'empty' nodes are nodes that are known not to be inserted in an rbtree */
#define RB_EMPTY_NODE(node)  \
	((node)->__rb_parent_color == (uintptr_t)(node))
#define RB_CLEAR_NODE(node)  \
	((node)->__rb_parent_color = (uintptr_t)(node))

static inline void rb_link_node(struct rb_node *node, struct rb_node *parent,
                                struct rb_node **rb_link)
{
    node->__rb_parent_color = (uintptr_t)parent;
    node->rb_left = node->rb_right = NULL;

    *rb_link = node;
}

extern void rb_insert_color(struct rb_node *, struct rb_root *);

static inline void rb_insert_color_cached(struct rb_node *node,
                                          struct rb_root_cached *root,
                                          bool leftmost)
{
    if (leftmost)
        root->rb_leftmost = node;
    rb_insert_color(node, &root->rb_root);
}

struct rb_node *rb_add_cached(struct rb_node *node, struct rb_root_cached *tree,
                              bool (*less)(struct rb_node *, const struct rb_node *));

struct rb_node *rb_erase_cached(struct rb_node *node, struct rb_root_cached *root);

struct rb_node *rb_next(const struct rb_node *node);
